let http = require('http');
let net = require('net');
let url = require('url');
let createUdp = require("./createUdp.js").createUdp;
let sendBroad = require("./borderServer.js").sendBroad;
let configpath = require("./getConfig").ev.path;
let config1 = require(configpath);
let clientset = new Set();// 当前连接的

function createtcpProxy(tcplistenport, tcplistenIp, tcpturnport, tcpturnIp) {
    console.log(`tcp桥接${tcplistenIp}:${tcplistenport}<==>${tcpturnIp}:${tcpturnport}`);
    let tcpserver = net.createServer(function (from) {
        let addressstr = from.remoteAddress + ":" + from.remotePort;
        handAddr(addressstr);
        let to = net.createConnection({
            host: tcpturnIp,
            port: tcpturnport
        });
        to.setTimeout(3000);
        to.on("timeout", function () {
            from.close();
        });

        from.pipe(to);
        to.pipe(from);// 转发
        from.on("end", function () {
            clientset.delete(this.remoteAddress + ":" + this.remotePort);
            // console.log(this.remoteAddress+":"+this.remotePort)
        });
        from.on("error", function () {
            clientset.delete(this.remoteAddress + ":" + this.remotePort);
        })
    });
    tcpserver.listen(tcplistenport.toString(), tcplistenIp);// 监听
    tcpserver.on('error', function (error) {
        console.log('error事件：服务端异常：' + error.message);
    });

}// 单例
//createtcpProxy(config1.tcplistenport, config1.tcplistenIp, config1.tcpturnport, config1.tcpturnIp);


function handAddr(addressstr) {
    if (!clientset.has(addressstr)) {
        clientset.add(addressstr);
        sendBroad(`from:${addressstr},go:${config1.go}`);
    }

}
process.on('uncaughtException', function () {
});

function initServer() {
    if (config1.list) {
        list.forEach(function (element) {
            createtcpProxy(element.tcplistenport, element.tcplistenIp, element.tcpturnport, element.tcpturnIp);
        }, this);

    }
}
module.exports.initServer = initServer;
module.exports.createtcpProxy = createtcpProxy;